package com.alinesno.infra.base.search.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alinesno.infra.base.search.entity.DatasetClientEntity;
import com.alinesno.infra.base.search.mapper.DatasetClientMapper;
import com.alinesno.infra.base.search.service.IDatasetClientService;
import com.alinesno.infra.common.core.service.impl.IBaseServiceImpl;
import com.alinesno.infra.common.facade.datascope.PermissionQuery;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.lang.exception.RpcServiceRuntimeException;

/**
 * 资产编目Service业务层处理
 *
 * @author luoxiaodong
 * @since 1.0.0
 */
@Slf4j
@Service
public class DatasetClientServiceImpl extends IBaseServiceImpl<DatasetClientEntity, DatasetClientMapper> implements IDatasetClientService {

    private static final String DEFAULT_KEY_PREFIX = "ds-";

    @Override
    public String generateApiKey(Long userId, PermissionQuery query) {

        LambdaQueryWrapper<DatasetClientEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DatasetClientEntity::getOperatorId, userId);

        // 如果不存在，则添加默认的客户端
        DatasetClientEntity client = getOne(queryWrapper);
        if (client == null) {
            client = new DatasetClientEntity();

            client.setOperatorId(query.getOperatorId());
            client.setOrgId(query.getOrgId());
            client.setDepartmentId(query.getDepartmentId());

            client.setOperatorId(userId);
            client.setApiKey(DEFAULT_KEY_PREFIX + IdUtil.getSnowflakeNextIdStr());
            client.setKeyStatus(1);

            save(client);
        }

        return client.getApiKey();

    }

    @Override
    public String updateKeyStatus(Long userId, PermissionQuery query) {

        LambdaQueryWrapper<DatasetClientEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DatasetClientEntity::getOperatorId, userId);
        DatasetClientEntity client = getOne(queryWrapper);

        if (client == null) {
            throw new RpcServiceRuntimeException("认证信息不存在.");
        }

        // 复制组织权限信息
        client.setOperatorId(query.getOperatorId());
        client.setOrgId(query.getOrgId());
        client.setDepartmentId(query.getDepartmentId());

        client.setApiKey(DEFAULT_KEY_PREFIX + IdUtil.getSnowflakeNextIdStr());
        updateById(client);

        return client.getApiKey();

    }

    @Override
    public String getCurrentUserApiKey(Long userId) {
        DatasetClientEntity client = getOne(
                new LambdaQueryWrapper<DatasetClientEntity>()
                        .eq(DatasetClientEntity::getOperatorId, userId)
                        .eq(DatasetClientEntity::getKeyStatus, 1) // 只返回启用状态的密钥
        );

        return (client != null) ? client.getApiKey() : null;
    }
}
